package com.dotflat.check.service;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class TianBoMqttConfig {

    @Value("${iot.checker.tianbo.mqtt.host}")
    private String mqtt_host;

    @Value("${iot.checker.tianbo.mqtt.port}")
    private int mqtt_port;

    @Value("${iot.checker.tianbo.mqtt.clientId}")
    private String mqtt_client_id;

    @Value("${iot.checker.tianbo.mqtt.account}")
    private String mqtt_account;

    @Value("${iot.checker.tianbo.mqtt.password}")
    private String mqtt_password;


    @Bean
    public MqttClient tianboMqttClient() throws MqttException {


        String broker = "tcp://" + mqtt_host + ":" + mqtt_port;
        MqttClient mqttClient = new MqttClient(broker, mqtt_client_id);

        // 设置回调（可选）
        mqttClient.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
                log.info("Connection lost: " + cause.getMessage());
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) {
                log.info("Message received: " + message.toString());
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                log.info("Message delivered: " + token.getMessageId());
            }
        });

        MqttConnectOptions options = new MqttConnectOptions();
        options.setAutomaticReconnect(true);

        options.setCleanSession(true); // 设置为干净会话
        options.setUserName(mqtt_account);   // 设置用户名
        options.setPassword(mqtt_password.toCharArray()); // 设置密码

        // 连接到代理
        mqttClient.connect(options);
        log.info("Connected to broker: " + broker);

        return mqttClient;
    }
}
